package com.vlin.api.client.defaut;

import org.json.JSONObject;

import com.vlin.api.client.AbstractClient;
import com.vlin.api.client.ApiClient;
import com.vlin.api.client.Client;
import com.vlin.api.client.Method;
import com.vlin.api.client.Params;
import com.vlin.api.client.exception.ClientException;
import com.vlin.api.client.request.ParamsProducer;
import com.vlin.api.client.request.defaut.DefaultParamsProducer;
import com.vlin.constant.API;
import com.vlin.token.Token;
import com.vlin.token.TokenManager;
import com.vlin.token.defaut.DefaultTokenManager;

public class DefaultClient extends AbstractClient {
	
	private ApiClient apiClient = new DefaultedApiClient();
	private TokenManager tokenManager = new DefaultTokenManager();
	private ParamsProducer paramsProducer = new DefaultParamsProducer();
	private String host;
	private API api;

	public DefaultClient(String host, API api) {
		if(host == null || api == null) {
			throw new ClientException();
		}
		this.host = host;
		this.api = api;
		apiClient.setHost(host);
		apiClient.setAPI(api);
		tokenManager.setApiClient(apiClient);
		tokenManager.getTokenRefresher().setParamsProduer(paramsProducer);

	}
	
	public static Client build(String host, API api) {
		
		return new DefaultClient(host, api);
	}

	@Override
	public JSONObject send(String uri, Params params, Method method) {
		Token token = tokenManager.getToken();
		Params newParams = paramsProducer.produce(api, token);
		newParams.setParams(params);
		return apiClient.send(uri, newParams, method);
	}


	@Override
	public ApiClient getApiClient() {
		
		return this.apiClient;
	}

	@Override
	public TokenManager getTokenManager() {
		
		return this.tokenManager;
	}

	@Override
	public String getHost() {
		
		return this.host;
	}

	@Override
	public void apiClient(ApiClient apiClient) {
		this.apiClient = apiClient;
		
	}

	@Override
	public void tokenManager(TokenManager tokenMnager) {
		this.tokenManager = tokenMnager;
		
	}


	@Override
	public void host(String host) {
		this.host = host;
		
	}


	@Override
	public ParamsProducer getParamsProducer() {
		
		return this.paramsProducer;
	}

	@Override
	public void paramsProducer(ParamsProducer paramsProducer) {
		this.paramsProducer = paramsProducer;
		
	}


	@Override
	public void setAPI(API api) {
		this.api = api;
	}


	@Override
	public API getAPI() {
		
		return this.api;
	}

}
